import db from '@dfeidao/atom-nodejs/db';
import query from '@dfeidao/atom-nodejs/db/query';
import { IncomingHttpHeaders } from 'http';

import { systemid } from '../atom/config';
interface Message {
	productid: string;
	class_id: string;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string[];
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}
interface A {
	student_no: string;
	parent_number: string;
	phone: string;
	parent_name: string;
	openid: string;
	usercode: string;

}
export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {

	const { exec, prepare } = db.query(action_id, session_id, systemid);

	prepare('class_student', ['student_no', 'class_id', 'student_name'], { productid: message.productid, class_id: message.class_id }, 199, 1, [], []);
	const [d] = await exec<A>();
	const student_no = new Array();
	if (d.length > 0) {
		d.forEach((i) => {
			student_no.push(i.student_no);
		});
	}

	// , 'grade', 'grade_no'
	prepare('parent_information', ['parent_number', 'parent_name', 'phone', 'student_no'], { productid: message.productid, student_no: { $in: student_no }, is_message_receiver: '1' }, 199, 1, [], []);
	const [d2] = await exec<A>();
	const phone = new Array();
	if (d2.length > 0) {
		d2.forEach((i) => {
			phone.push(i.phone);
		});
	}
	const { prepare: p, exec: e } = query(action_id, session_id, "12");
	p('pub_user_thirdpart_openid', ['usercode', 'openid', "login_type", "productid", "is_disabled"], { productid: message.productid, usercode: { $in: phone } }, 10, 1, [], []);//
	const [d3] = await e<A>();
	d.forEach((i) => {
		i.parent_number = '';
		i.parent_name = '';
		i.phone = '';
		d2.forEach((j) => {
			if (i.student_no === j.student_no) {
				i.parent_number = j.parent_number;
				i.parent_name = j.parent_name;
				i.phone = j.phone;
			}

		});
	});
	d.forEach((i) => {
		i.openid = '';
		d3.forEach((j) => {
			if (i.phone === j.usercode) {
				i.openid = j.openid;
			}

		});
	});
	return { data: { dataArray: d } } as IWebResult;
}
